package com.yunbiao.ybbusstopplate.serialport.agreement;

import android.text.TextUtils;
import com.yunbiao.ybbusstopplate.utils.BytesUtils;
import com.yunbiao.ybbusstopplate.utils.StringUtils;

public class AgreementDataTool {
//    private static AgreementDataTool agreementDataTool;

    private AgreementDataReceive dataReceive;

    private StringBuilder hexString=null;

    private String device="";

    private String sHex,eHex;

//    private AgreementDataTool(){}
//
//    public static AgreementDataTool getInstance(){
//        if (agreementDataTool==null){
//            agreementDataTool=new AgreementDataTool();
//        }
//        return agreementDataTool;
//    }


    public void setDataReceive(AgreementDataReceive dataReceive){
        this.dataReceive=dataReceive;
    }

    public void setSHex(String sHex){
        this.sHex=sHex;
    }
    public void setEHex(String eHex){
        this.eHex=eHex;
    }
    public void handleData(byte[] bytes){
        if (bytes == null || bytes.length <= 0) {
            return;
        }
        if (hexString == null) {
            hexString = new StringBuilder();
        }

        byte start = bytes[0];
        String startHex = BytesUtils.byteToHex(start);

        byte end = bytes[bytes.length - 1];
        String endHex = BytesUtils.byteToHex(end);

        //开始
        if (sHex.equals(startHex)) {
//            Log.d(TAG, "-----------start---------");
            hexString.delete(0, hexString.length());
            device = BytesUtils.byteToHex(bytes[1]);
        }
        //存储数据
        hexString.append(BytesUtils.bytesToHex(bytes));
        //结束
        if (eHex.equals(endHex)) {
//            Log.d(TAG, "-----------end---------");
//            Log.d(TAG, "--->" + hexString.toString());
            String splitStr = sHex + device;
            String[] hexArray = hexString.toString().split(splitStr);
            for (String ss : hexArray) {
                if (ss != null && !"".equals(ss)) {
//                    System.out.println("bb10" + ss);
                    byte[] byteArray = BytesUtils.hexToByteArray(splitStr + ss);
                    if (dataReceive!=null){
                        dataReceive.onDataReceive(byteArray);
                    }
                }
            }
        }
    }


    public interface AgreementDataReceive{
        void onDataReceive(byte[] datas);
    }
}
